package com.example.common;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

import java.util.ArrayList;
import java.util.List;


/**
 * 对象转换
 */
@Slf4j
public class DozerUtils {

    private static Mapper dozerBeanMapper = new DozerBeanMapper();

    /**
     * 实体转换
     *
     * @param source 原实体
     * @param target 目标实体
     */
    public static void conversion(Object source, Object target) {
        dozerBeanMapper.map(source, target);
    }

    /**
     * 将Object对象转成实体
     *
     * @param source      原对象
     * @param targetClass 目标实体
     * @param <T>         泛型
     * @return <T> T
     */
    public static <T> T conversion(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }

        try {
            targetClass.newInstance();
        } catch (Exception e) {
            log.error("conversionList Exception : ", e);
        }
        return dozerBeanMapper.map(source, targetClass);
    }

    /**
     * 集合对象之间的转换
     *
     * @param source      原集合
     * @param targetClass 目标集合
     * @param <T>         泛型
     * @return List<T>
     */
    public static <T> List<T> conversionList(List<?> source, Class<T> targetClass) {
        ArrayList<T> result = null;
        if (source != null) {
            result = new ArrayList<>(source.size());
            if (!source.isEmpty()) {
                for (Object obj : source) {
                    result.add(conversion(obj, targetClass));
                }
            }
        }
        return null == result ? Lists.newArrayList() : result;
    }
}
